import com.alibaba.fastjson.JSON;
import com.softlab.logsystem.core.model.LogVo;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author LiXiwen
 * @date 2020/1/7 20:27
 */
@Component
public final class LoggerUtil {
    /**
     * Java8日期格式化，线程安全
     */
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 日志发送接口
     */
    public static final String URI = "http://118.24.41.50:8081/log/send";

    public void info(String msg) {
        send(new Exception().getStackTrace()[1].getClassName() + " : " + new Exception().getStackTrace()[1].getMethodName(), "info", msg);
    }

    public void warn(String msg) {
        send(new Exception().getStackTrace()[1].getClassName() + " : " + new Exception().getStackTrace()[1].getMethodName(),"warn", msg);
    }

    public void error(String msg) {
        send(new Exception().getStackTrace()[1].getClassName() + " : " + new Exception().getStackTrace()[1].getMethodName(),"error", msg);
    }

    public void debug(String msg) {
        send(new Exception().getStackTrace()[1].getClassName() + " : " + new Exception().getStackTrace()[1].getMethodName(),"debug", msg);
    }

    public void send(String className, String level, String content) {
        synchronized(LoggerUtil.class) {
            LogVo logVo = new LogVo();
            logVo.setLevel(level);
            // 设置自己的项目名称
            //logVo.setApplication(APPLICATION_NAME);
            logVo.setContent(content);
            logVo.setTag(className);
            logVo.setTimestamp(LocalDateTime.now().format(dtf));

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(URI);
            ((HttpEntityEnclosingRequest) httpPost).setEntity(
                    new StringEntity(JSON.toJSONString(logVo),
                            ContentType.create("application/json", "UTF-8")));
            try {
                int code = 200;
                CloseableHttpResponse response = httpClient.execute(httpPost);
                if (code != response.getStatusLine().getStatusCode()) {
                    System.out.println("LoggerUtil : " + "send log error : " + response.getStatusLine().getStatusCode());
                }
            } catch (IOException e) {
                System.out.println("LoggerUtil : " + "send log error : " + e.getMessage());
            }
        }

    }

}
